package com.weiiew.backend.operationUtils;

import com.weiiew.backend.entity.ScriptFile;
import com.weiiew.backend.operation.ComputerOperation;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.Serializable;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.*;

/**
 * @Description 实现 Serializable 以支持序列化存储
 * @Author 魏锴
 * @Date 2025/4/26
 */
@ToString
@Getter
@Setter
public class OperationSequence implements Serializable, Iterable<ComputerOperation> {
    private static final long serialVersionUID = 1L;
    private String name;
    private transient long executorTime;
    private final List<ComputerOperation> operations = new ArrayList<>();
    // 新增元数据快速读取方法（避免加载全部操作数据）

    // 元数据快速读取方法改进版
    public static ScriptFile readMetadata(Path file) throws IOException {
        try (BufferedReader reader = Files.newBufferedReader(file)) {
            String name = reader.readLine();
            int operationCount = Integer.parseInt(reader.readLine());
            long executorTime = Long.parseLong(reader.readLine());
            return new ScriptFile(name, operationCount, executorTime);
        } catch (Exception e) {
            throw new IOException("文件格式损坏", e);
        }
    }

    private static OperationSequence readObject(BufferedReader reader) throws IOException {
        OperationSequence sequence = new OperationSequence();
        sequence.name = reader.readLine();
        int size = Integer.parseInt(reader.readLine());
        sequence.executorTime = Long.parseLong(reader.readLine());

        for (int i = 0; i < size; i++) {
            String line = reader.readLine();
            sequence.operations.add(ComputerOperation.deserialize(line));
        }
        return sequence;
    }

    public static OperationSequence loadFromFile(String filePath) throws IOException {
        try (BufferedReader reader = Files.newBufferedReader(Paths.get(filePath))) {
            return readObject(reader);
        }
    }

    // 自定义序列化格式
    private void writeObject(BufferedWriter writer) throws IOException {
        writer.write(name);
        writer.newLine();
        writer.write(String.valueOf(operations.size()));
        writer.newLine();
        writer.write(String.valueOf(executorTime));
        writer.newLine();

        for (ComputerOperation operation : operations) {
            writer.write(operation.toDescriptionString());
            writer.newLine();
        }
    }

    // 序列化辅助方法
    // 序列化辅助方法
    public void saveToFile(Path filePath) throws IOException {
        this.name = filePath.getFileName().toString().replaceFirst("[.][^.]+$", "");
        this.executorTime = !operations.isEmpty() ?
                operations.get(operations.size() - 1).getTimestamp() :
                System.currentTimeMillis();

        try (BufferedWriter writer = Files.newBufferedWriter(filePath, StandardOpenOption.CREATE_NEW)) {
            this.writeObject(writer);
        }
    }

    // 基础操作方法
    public synchronized void addOperation(ComputerOperation operation) {
        operations.add(Objects.requireNonNull(operation));
    }

    public void addAllOperations(OperationSequence sequence) {
        operations.addAll(sequence.getOperations());
    }

    public boolean removeOperation(ComputerOperation operation) {
        return operations.remove(operation);
    }

    public ComputerOperation removeOperation(int index) {
        return operations.remove(index);
    }

    public void clearOperations() {
        operations.clear();
    }

    // 保留原有不可修改的访问方式（安全访问）
    public List<ComputerOperation> getOperations() {
        return Collections.unmodifiableList(operations);
    }

    // 新增可修改的访问方式（需谨慎使用）
    public List<ComputerOperation> getMutableOperations() {
        return operations; // 返回独立副本
    }

    public int size() {
        return operations.size();
    }

    public boolean isEmpty() {
        return operations.isEmpty();
    }

    // 迭代器实现
    @Override
    public Iterator<ComputerOperation> iterator() {
        return operations.iterator();
    }


    // 构建器模式（可选）
    public static class Builder {
        private final OperationSequence sequence = new OperationSequence();

        public Builder addOperation(ComputerOperation operation) {
            sequence.addOperation(operation);
            return this;
        }

        public OperationSequence build() {
            return sequence;
        }
    }
}